package com.hbzhit.common.extension;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.hbzhit.common.annotation.SysLog;
import com.hbzhit.common.entity.BaseEntity;
import com.hbzhit.common.utils.PageUtils;
import com.hbzhit.common.utils.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Controller基类
 * @author DING
 * @date 2021/4/2 17:26
 * @version 1.0
 **/
public class BaseController<M extends IBaseService<T>, T extends BaseEntity> {

	@Autowired
	protected M baseService;

	/**
	 * 分页列表
	 */
	@ApiOperation(value = "分页列表", notes = "传入高级查询参数")
	@GetMapping("/page")
	public R<PageUtils<T>> page(@RequestParam @ApiParam(hidden = true) Map<String, Object> params){
		return R.ok(baseService.page(params));
	}

	/**
	 * 无分页列表
	 */
	@ApiOperation(value = "列表", notes = "传入高级查询参数")
	@GetMapping("/list")
	public R<List<T>> list(@RequestParam @ApiParam(hidden = true) Map<String, Object> params){
		return R.ok(baseService.list(params));
	}

	/**
	 * 信息
	 */
	@ApiOperation(value = "根据ID查询详细数据")
	@GetMapping("/info/{id}")
	public R<T> info(@PathVariable("id") Long id){
		return R.ok(baseService.getById(id));
	}

	/**
	 * 新增
	 */
	@ApiOperation(value = "新增数据")
	@PostMapping("/save")
	public R<T> save(@RequestBody T t){
		baseService.save(t);
		return R.ok(t);
	}

	/**
	 * 修改
	 */
	@ApiOperation(value = "更新数据")
	@PostMapping("/update")
	public R<T> update(@RequestBody T t){
		baseService.updateById(t);
		return R.ok(t);
	}

	/**
	 * 批量更新
	 */
	@ApiOperation(value = "批量更新")
	@SysLog("批量更新")
	@PostMapping("/updateBatch")
	public R<Object> updateBatch(@RequestBody List<T> list){
		baseService.updateBatchById(list);
		return R.ok();
	}

	/**
	 * 删除
	 */
	@ApiOperation(value = "删除数据")
	@PostMapping("/delete")
	public R<Object> delete(@RequestBody Long[] ids){
		baseService.removeByIds(Arrays.asList(ids));
		return R.ok();
	}

	/**
	 * 导出
	 */
	@ApiOperation(value = "导出")
	@GetMapping("/export")
	public ResponseEntity<byte[]> exportExcel(@RequestParam @ApiParam(hidden = true) Map<String, Object> params) throws IOException {
		return baseService.exportExcel(params);
	}

	/**
	 * 导入
	 */
	@ApiOperation(value = "导入")
	@PostMapping("/import")
	@SysLog("导入")
	public R<Object> importExcel(@RequestParam(value = "file",required = false) MultipartFile file) throws Exception {
		//执行导入
		ExcelImportResult<T> result = baseService.importExcel(file);

		return R.ok("成功导入" + result.getList().size() + "条数据");
	}

}
